package com.huc.rabbit.mq.provider;

import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.UUID;

@Component
public class RabbitSender implements RabbitTemplate.ConfirmCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Value("${mq.exchange}")
    private String exchange;

    @Value("${mq.ingate.queue}")
    private String ingateQueue;

    @PostConstruct
    private void init() {
        //启用事务模式,不能开确认回调
        rabbitTemplate.setConfirmCallback(this);
//        rabbitTemplate.setReturnCallback(this);
//        rabbitTemplate.setChannelTransacted(true);
//        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
    }

//    @Transactional(rollbackFor = Exception.class, transactionManager = "rabbitTransactionManager")
    public void sendIngateQueue(String msg) {
        System.out.println("进闸消息已发送:" + msg);
        //设置自定义反馈消息
        String uuid = UUID.randomUUID().toString();
        CorrelationData correlationData = new CorrelationData();
        correlationData.setId(uuid);

        //并不存在名为“exchange-dog”的exchange
        try {
            rabbitTemplate.convertAndSend(exchange, ingateQueue, msg, correlationData);
        } catch (Exception e) {
            System.out.println("投递消息到交换机失败....等待回调确认");
        }
    }

    //消息回退机制
//    @Override
//    public void returnedMessage(Message message, int i, String s, String s1, String s2) {
//        System.out.println("消息被退回：" + message);
//    }

    //消息确认机制
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (!ack) {
            System.out.println("correlationData:" + correlationData);
            System.out.println("ack:" + ack);
            System.out.println("cause:" + cause);
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //重新投递消息
            rabbitTemplate.convertAndSend(exchange, ingateQueue, "重新投递消息", correlationData);
        } else {
            System.out.println("ack:" + ack);
        }
    }
}
